package com.xyzwps.paimon.katheryne.commons.dbmapper;

import io.helidon.dbclient.DbColumn;

public final class MapDbColumn {

    public static int toIntValue(DbColumn col) {
        if (Number.class.isAssignableFrom(col.javaType())) {
            return col.get(Number.class).intValue();
        }
        throw castError("int value", col);
    }

    public static long toLongValue(DbColumn col) {
        if (Number.class.isAssignableFrom(col.javaType())) {
            return col.get(Number.class).longValue();
        }
        throw castError("long value", col);
    }

    public static boolean toBooleanValue(DbColumn col) {
        if (Number.class.isAssignableFrom(col.javaType())) {
            return col.get(Number.class).intValue() != 0;
        }
        if (Boolean.class.equals(col.javaType())) {
            return col.get(Boolean.class);
        }
        throw castError("boolean value", col);
    }

    public static String toString(DbColumn col) {
        return col.getString();
    }

    public static <T> T to(DbColumn col, Class<T> c) {
        var map = ColumnMappers.get(c);
        if (map == null) {
            throw new IllegalStateException("Cannot cast db column to " + c.getCanonicalName() + ": no mapper found.");
        }
        return map.apply(col);
    }

    private static RuntimeException castError(String targetType, DbColumn col) {
        return new IllegalStateException("Cannot cast db column to " + targetType + " from " + col.javaType().getCanonicalName());
    }

    private MapDbColumn() throws IllegalAccessException {
        throw new IllegalAccessException("???");
    }
}
